from __future__ import division
import numpy as np

def SimpleMovingAverage(value_array, length):
	
	if value_array is not None:
	
		smv = np.empty(value_array.shape)
	
		for i in range(len(value_array)):
		
			start = np.maximum(i-length+1, 0)
			end = i + 1
			smv[i] = np.mean(value_array[start:end,:], 0)
			
		return smv
		
def RelativeStrengthIndex(value_array, length):

	if value_array is not None:
	
		rsi = np.empty(value_array.shape)
	
		for i in range(len(value_array)):
		
			start = np.maximum(i-length+1, 0)
			end = i + 1
			max = np.max(value_array[start:end,:], 0)
			min = np.min(value_array[start:end,:], 0)
			current = value_array[i,:]
			breadth = max - min
			breadth[breadth <= 0] = 1.0 #avoiding dividend by zero
			rsi[i] = (current - min)/breadth
			
		return rsi
		
def AverageTrueRange(value_array, length):
#Type of value_array is 3-d array with [time, security, [high,low,close]]
	
	if value_array is not None:
	
		atr = np.empty(value_array.shape[:2])
		atr[0] = value_array[0,:,0] - value_array[0,:,1]
		
		for i in range(1, len(value_array)):
		
			tr = np.max([value_array[i,:,0] - value_array[i,:,1],
			value_array[i,:,0] - value_array[i-1,:,2],
			value_array[i-1,:,2] - value_array[i,:,1]], 0)
			
			atr[i] = ((length - 1)*atr[i - 1] + tr)/length
			
		return atr
		